<!--
 * @Descripttion: 采购入库
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-16 10:21:11
 -->
<template>
  <div>
    <el-main>
      <!-- {{ dataObj }}<br> -->
      <!-- purchaseId: {{ purchaseId }} -->
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>单号: {{ dataObj.purchaseNumber }}</span>
        </div>
        <el-form
          ref="purchaseForm"
          :inline="true"
          :model="dataObj"
          :rules="ruleValidator"
          label-position="left"
          label-width="100px"
          size="mini"
        >
          <el-form-item label="供应商:" prop="supplierId">
            <el-select v-model="dataObj.supplierId" :filter-method="getSuppilers" filterable placeholder="请选择">
              <el-option
                v-for="item in optionsData.supplier"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应付金额:" prop="amountPayable">
            <el-input v-model.number="dataObj.amountPayable" disabled />
          </el-form-item>
          <el-form-item label="实付金额:" prop="amountPaid">
            <el-input v-model.number="dataObj.amountPaid" />
          </el-form-item>
          <el-form-item label="是否收款:">
            <el-switch
              v-model="dataObj.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#cccccc"
            />
          </el-form-item>
          <el-form-item label="单据日期:">
            <el-date-picker
              v-model="dataObj.purchaseDate"
              type="datetime"
            />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="dataObj.remarks" style="width:400px;" />
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSave({readd:true})">保存并新增</el-button>
          <el-button type="success" size="medium" :loading="btnLoading.save" @click="btnSave({readd:false})">保 存</el-button>
        </div>
      </el-card>
      <div class="margin-t10">
        <div>
          <el-button type="primary" size="medium" @click="btnAddTableData">添 加</el-button>
          <el-button type="danger" size="medium" @click="btnDelTableData">删 除</el-button>
        </div>
        <el-table
          ref="productTable"
          v-loading="tableLoading.goodsSelect"
          :data="tableData.goodsSelect"
          style="width: 100%"
          border
          @selection-change="onSelectionChange"
        >
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column label="商品编号" width="100" prop="code" align="left" />
          <el-table-column label="商品名称" :show-overflow-tooltip="true" width="200" prop="name" align="left" />
          <el-table-column label="型号" width="100" prop="model" align="left" />
          <el-table-column label="类别" width="100" prop="typeName" align="left" />
          <el-table-column label="单位" width="60" prop="unit" align="center" />
          <el-table-column label="单价" width="100" prop="price" align="right" />
          <el-table-column label="数量" width="100" align="center" fixed="left">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.num" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="总额" width="130" :show-overflow-tooltip="true" prop="total" align="right" fixed="left">
            <template slot-scope="scope">
              {{ scope.row | goodAmount }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import GoodsList from '@/views/goods'
import { saveData as savePurchase, getReturnNumber, listDataById, listGoods } from '@/api/return-list'
import { comboList } from '@/api/supplier'
import moment from 'moment'
import { amount } from '@/libs/tools.js'
import { jump2pages } from './mixins'

export default {
  name: 'PurchaseDetail',
  filters: {
    goodAmount: function(row) {
      return amount(row.price).multiply(row.num).format()
    }
  },
  mixins: [oftenuse, jump2pages],
  props: {
    operation: {
      type: String,
      default: 'save',
      validator: (value) => {
        return ['save', 'update'].indexOf(value) !== -1
      }
    },
    purchaseId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      optionsData: { supplier: [] },
      ruleValidator: {
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ],
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      }
    }
  },
  computed: {
    totalAmount: function() {
      const tableData = this.getTableData('goodsSelect')
      if (!tableData.length) return 0
      let result = 0
      tableData.forEach(item => {
        result = amount(result).add(amount(item.price).multiply(item.num).format()).format()
      })
      return result
    }
  },
  watch: {
    'totalAmount': {
      handler(val) {
        if (this.operation === 'update') return
        this.$set(this.dataObj, 'amountPayable', val)
        this.$set(this.dataObj, 'amountPaid', val)
      },
      immediate: true
    }
  },
  created() {
    if (!this.operation) throw new Error('必须传入操作符operation!')
    this.initData()
    this.$bus.$on('on-goods-select-sure', (selectData) => {
      const data = this.formatGoodsData2OrderDetail(selectData)
      this.getTableData('goodsSelect').push(...data)
    })
  },
  methods: {
    btnAddTableData() {
      this.$layer.iframe.addSingle({
        title: '选择商品',
        area: ['1000px', '400px'],
        name: 'iframe-goods',
        content: {
          content: GoodsList,
          props: {
            oper: 'select'
          }
        }
      })
    },
    btnDelTableData() {
      const selectData = this.getTableSelectionData('goodsSelect')
      if (!selectData) return
      const ids = selectData.map(item => { return item.code })
      const tableData = this.getTableData('goodsSelect')
      for (let i = 0; i < tableData.length; i++) {
        const item = tableData[i]
        if (ids.indexOf(item.code) !== -1) {
          this.$delete(tableData, i)
          i--
        }
      }
    },
    btnSave({ readd }) {
      this.handleValid('purchaseForm').then(() => {
        const params = {
          returnList: this.dataObj,
          returnListGoodsList: this.formatParamsGoodsData(this.getTableData('goodsSelect'))
        }
        this.setBtnLoading('save', true)
        this.saveReturnBill(params).then(() => {
          if (readd) {
            this.jump2purchaseDetail({ operation: 'save' })
          }
          this.setBtnLoading('save', false)
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      })
    },
    // api
    getGoodTotal(goodRow) {
      return amount(goodRow.num).multiply(goodRow.price).format()
    },
    formatParamsGoodsData(goodList) {
      goodList.forEach(item => {
        item.total = this.getGoodTotal(item)
      })
      return goodList
    },
    /**
     * 把商品数据转化成票据商品详情的数据
     */
    formatGoodsData2OrderDetail(tableData) {
      tableData.forEach(item => {
        item.goodsId = item.id
        item.price = item.purchasingPrice
      })
      return tableData
    },
    getSuppilers(params) {
      comboList(params).then(res => {
        if (res.data.flag) {
          this.$set(this.optionsData, 'supplier', res.data.data)
        }
      })
    },
    clearData() {
      this.dataObj = {}
      this.setTableData('goodsSelect', [])
    },
    /**
     * 新增状态初始化
     */
    initSaveData() {
      this.clearData()
      this.setPurchaseNumber()
      const date = moment().format('YYYY-MM-DD HH:mm:ss')
      this.$set(this.dataObj, 'purchaseDate', date)
    },
    getOrderGoods(orderId) {
      listGoods(orderId).then(res => {
        if (!res.data.flag) return this.$notify.error({ title: '获取采购单商品失败!' })
        this.setTableData('goodsSelect', res.data.data)
      })
    },
    getOrderData(orderId) {
      listDataById(orderId).then(res => {
        if (!res.data.flag) return this.$notify.error({ title: '获取采购单失败!' })
        const data = res.data.data
        this.dataObj = data
        this.optionsData.supplier.push({ id: data.supplierId, name: data.supplierName })
      })
    },
    initUpdateData() {
      const purchaseId = this.purchaseId
      this.getOrderGoods(purchaseId)
      this.getOrderData(purchaseId)
    },
    initData() {
      if (this.operation === 'save') this.initSaveData()
      if (this.operation === 'update') this.initUpdateData()
    },
    /**
     * 设置采购退货单号
     */
    setPurchaseNumber() {
      getReturnNumber().then(res => {
        if (res.data.flag) {
          this.$set(this.dataObj, 'purchaseNumber', res.data.data)
        }
      })
    },
    /**
     * 保存采购退货订单
     */
    saveReturnBill(params) {
      return new Promise((resolve, reject) => {
        savePurchase(params).then(res => {
          resolve(res)
          if (res.data.flag) return this.$notify.success({ title: '保存成功！' })
          this.$notify.error({ title: '保存失败！', message: res.data.message || '' })
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    // on
    onSelectionChange(selectData) {
      this.setTableSelectionData('goodsSelect', selectData)
    }
  }
}
</script>

<style scoped>
</style>
